package com.jy.control.file;


import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@RestController
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/index")
    public @ResponseBody String index(){
        return "file/index";
    }

    @RequestMapping("/upload")
    public void upload (@RequestParam("file")MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        BufferedOutputStream outputStream =  new BufferedOutputStream(new FileOutputStream(originalFilename));
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();
    }

    @RequestMapping("/download")
    public ResponseEntity download() throws IOException {
        HttpHeaders headers = new HttpHeaders();
        FileSystemResource fileSystemResource = new FileSystemResource("doctor.jpg");
        headers.add("Content-Disposition","attachment;filename=123.jpg");
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(fileSystemResource.contentLength())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(fileSystemResource.getInputStream()));

    }
}
